package org.dut.book.Controller;

import lombok.extern.slf4j.Slf4j;
import org.dut.book.Service.BookService;
import org.dut.book.model.BookInfo;
import org.dut.book.model.PageRequest;
import org.dut.book.model.PageResult;
import org.dut.book.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;

    /**
     * 获取图书列表
     */
    @RequestMapping("/getBookListByPage")
    public Result getBookListByPage(PageRequest pageRequest) {
        PageResult pageResult = bookService.getBookListByPage(pageRequest);
        return Result.success(pageResult);
    }

    @RequestMapping("/addBook")
    public Integer addBook(BookInfo book) {
        if(!StringUtils.hasLength(book.getBookName())||
        !StringUtils.hasLength(book.getAuthor()) ||
        book.getCount() == null ||
        book.getPrice() == null ||
        !StringUtils.hasLength(book.getPublish())||
        book.getCount()<0||book.getPrice()<0||
        book.getStatus()==null) {
            return 0;
        }
        return bookService.addBook(book);
    }

    //修改图书信息时，首先要获得图书信息
    @RequestMapping("/queryBookById")
    public BookInfo getBookById(Integer id) {
        if(id!=null&&id>0) {
            return bookService.queryBookById(id);
        }
        return null;
    }
    @RequestMapping("/updateBook")
    public Integer updateBook(BookInfo book) {
        if(book.getId()==null){
            //非法访问
            return -1;
        }
        try{
            //修改成功，返回修改行数
            return bookService.updateBook(book);
        } catch (Exception e) {
            log.error(e.getMessage());
            //修改失败
            return 0;
        }
    }

    // 删除图书 逻辑删除 设置图书状态为0
    @RequestMapping("/deleteBook")
    public Boolean deleteBookById(Integer id) {
        if(id!=null&&id>0) {
           return bookService.deleteBookById(id);
        }
        return false;
    }

    @RequestMapping("/batchDeleteBook")
    public Integer deleteBookByIds(Integer[] ids) {
        if(ids!=null&&ids.length>0) {
            return bookService.deleteBookByIds(ids);
        }else{
            return -1;
        }
    }

    @RequestMapping("/t1")
    public String t1() {
        int t=1/0;
        return "t1";
    }
}
